from prg.udp_data import UdpData
from prg.common.common_base import CommonBase


class UdpCommandInfo:
    def __init__(self, name, number=0, bytes_item=None):
        self.name_code = name
        self.number = int(number)
        self.bytes_item = bytes_item

    def set_bytes(self, entity, encryption=None):
        json_str = CommonBase.entity_to_json(entity)
        self.bytes_item = bytes(json_str, encoding='utf-8')
        if encryption is not None:
            self.bytes_item = CommonBase.xor_encryption(key=encryption, data=self.bytes_item)

    def send(self, socket_item, encryption=None):
        if len(self.bytes_item) > 0:
            cmd_item = UdpData()
            cmd_item.name = self.name_code
            cmd_item.number = self.number
            cmd_item.byte_data = self.bytes_item
            send_data = cmd_item.get_bytes(encryption=encryption)
            # print("send bytes length %s" % str(len(send_data)))
            socket_item.send(send_data)


